<template>

    <div style="margin: 20px;">
        <!--<button @click="getKlineDataForDefault">加载数据</button>
        <button @click="drawLine">显示K线图</button>-->
        <div id="myChart" style="width:auto;height:500px;"></div>
    </div>
</template>

<script>
    import httpUtil from '../../httpRequestUtil';

    export default {
        data() {
            return {
                /*用于查找的个股编号*/
                /*从个股列表传的tsCode参数*/
                symbol: this.$route.query.symbol,
                /*数量*/
                size: 90,
                endDate: this.$route.query.endDate,
                startDate: 0,
                /* 日线数据：开盘 收盘 最低 最高 */
                stockList: [],
                /* 日期 */
                times: [],
                /* 交易量 */
                vols: [],
                macds: [],
                difs: [],
                deas: [],
                stockInfo: null
            };
        },
        created(){

        },
        mounted() {
            this.getKlineDataForDefault();
            //this.getKlineData(this.startDate, this.endDate, this.size, this.symbol, this.times, this.datas, this.vols);
            this.drawLine();
        },
        watch: {
            '$route' (to, from) {
                this.$router.go(0);
            }
        },

        methods: {
            //时间格式化函数，此处仅针对yyyy-MM-dd hh:mm:ss 的格式进行格式化
            dateFormat:function(time) {
                var date=new Date(time);
                var year=date.getFullYear();
                /* 在日期格式中，月份是从0开始的，因此要加0
                 * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
                 * */
                var month= date.getMonth()+1<10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
                var day=date.getDate()<10 ? '0'+date.getDate() : date.getDate();
                var hours=date.getHours()<10 ? '0'+date.getHours() : date.getHours();
                var minutes=date.getMinutes()<10 ? '0'+date.getMinutes() : date.getMinutes();
                var seconds=date.getSeconds()<10 ? '0'+date.getSeconds() : date.getSeconds();
                // 拼接
                return year+month+day;
            },
            drawLine() {
                if (this.times != null) {
                    // 基于准备好的dom，初始化echarts实例

                    console.log('有数据啦：drawLine this.times =' + this.times);
                    this.echartsOption = this.getOption(this.times,this.stockList,this.vols, this.stockInfo);
                    if (this.echartsOption == null) {
                        //alert('echartsOption 为空 !');
                        console.log('echartsOption 为空 !');
                        return;
                    } else {
                        console.log('有数据啦：echartsOption 不为空');
                    }
                    if (this.myChart == null) {
                        this.myChart = this.$echarts.init(document.getElementById('myChart'));
                    }
                    // 绘制图表
                    this.myChart.setOption(this.echartsOption);
                }else{
                    alert('没有数据，不画线');
                }
            },
            getKlineDataForDefault() {
                this.getKlineData(this.startDate, this.endDate, this.size, this.symbol);
            },
            getKlineData(startDate, endDate, size, symbol) {
                let params = {
                    startDate: startDate,
                    endDate: endDate,
                    size: size,
                    tsCode: symbol
                };
                if(params.endDate == null){
                    params.endDate = this.dateFormat(new Date());
                }

                var that = this;

                let url = 'one/getKDataList';
                httpUtil.postData(url, params, function (data, message) {
                    if (data == null) {
                        return;
                    }

                    that.stockList = data.datas;
                    that.vols = data.vols;
                    that.times = data.times;
                    that.macds = data.macds;
                    that.difs = data.difs;
                    that.deas = data.deas;
                    that.stockInfo = data.entity;

                    if (that.echartsOption == null) {
                        //alert('echartsOption 为空 !');
                        console.log('echartsOption 为空 !');
                        that.echartsOption = that.getOption(that.times,that.stockList,that.vols, that.stockInfo);
                    } else {
                        console.log('有数据啦：echartsOption 不为空');
                    }
                    if (that.myChart == null) {
                        that.myChart = that.$echarts.init(document.getElementById('myChart'));
                    }
                    // 绘制图表
                    that.myChart.setOption(that.echartsOption);
                });

                /*this.axios({
                    method: 'get',
                    url: '/one/getKDataList',
                    params: {
                        startDate: startDate,
                        endDate: endDate,
                        size: size,
                        symbol: symbol
                    }
                }).then(function (response) {
                    console.log('response.data.datas=' + response.data.datas);
                    //this.myData = response.data;
                    this.myData.datas = response.data.datas;
                    this.myData.vols = response.data.vols;
                    this.myData.times = response.data.times;
                    this.myData.deas = response.data.deas;
                    this.myData.difs = response.data.difs;
                    this.myData.macds = response.data.macds;
                }.bind(this)).catch(function (error) {
                    alert(error);
                });*/

            },
            getOption(myTimes, myStockList, myVols, stockInfo) {
                if (myTimes == null || myTimes.length === 0) {
                    console.log('getOption: myTimes = null');
                    return null;
                }
                if (myStockList == null || myStockList.length === 0) {
                    console.log('getOption: myStockList = null');
                    return null;
                }
                if (myVols == null || myVols.length === 0) {
                    console.log('getOption: myVols = null');
                    return null;
                }
                if (stockInfo == null) {
                    console.log('getOption: stockInfo = null');
                    return null;
                }
                return {
                    title: {
                        text: stockInfo.name+'('+stockInfo.symbol+')',
                        left: 50
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter(params) {
                            //console.log('params =' + JSON.stringify(params[0]));
                            let res = '日期 ： ' + params[0].name;
                            res += '<br/>  开盘 : ' + params[0].value[1] + '  最高 : ' + params[0].value[4];
                            res += '<br/>  收盘 : ' + params[0].value[2] + '  最低 : ' + params[0].value[3];
                            return res;
                        }
                    },
                    /*图例控件,点击图例控制哪些系列不显示*/
                    legend: {
                        data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
                        selected: {
                            // 默认不显示
                            MA30: false,
                        }
                    },
                    axisPointer: {
                        link: [{
                            /*生成十字轴，控制3个x轴*/
                            xAxisIndex: [0, 1, 2]
                        }]
                    },
                    grid: [{
                        left: '5%',
                        right: '5%',
                        height: '55%'
                    }, {
                        left: '5%',
                        right: '5%',
                        top: '70%',
                        height: '15%'
                    }, {
                        left: '5%',
                        right: '5%',
                        top: '85%',
                        height: '15%'
                    }],
                    xAxis: [{
                        type: 'category',
                        data: myTimes,
                        scale: true,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        splitLine: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax'
                    }, {
                        type: 'category',
                        gridIndex: 1,
                        data: myTimes,
                        axisLabel: {show: false}
                    }, {
                        type: 'category',
                        gridIndex: 2,
                        data: myTimes,
                        axisLabel: {show: false}
                    }],
                    yAxis: [
                        {
                            scale: true,
                            splitArea: {
                                show: false
                            }
                        }, {
                            gridIndex: 1,
                            splitNumber: 3,
                            axisLine: {onZero: false},
                            axisTick: {show: false},
                            splitLine: {show: false},
                            axisLabel: {show: false}
                        }, {
                            gridIndex: 2,
                            splitNumber: 4,
                            axisLine: {onZero: false},
                            axisTick: {show: false},
                            splitLine: {show: false},
                            axisLabel: {show: true}
                        }
                    ],
                    dataZoom: [{
                        type: 'inside',
                        xAxisIndex: [0, 0],
                        start: 20,
                        end: 100
                    }, {
                        show: true,
                        xAxisIndex: [0, 1],
                        type: 'slider',
                        top: '97%',
                        start: 20,
                        end: 100
                    }, {
                        show: false,
                        xAxisIndex: [0, 2],
                        type: 'slider',
                        start: 20,
                        end: 100
                    }],
                    series: [{
                        name: 'K线周期图表(mystockdeal.cn)',
                        type: 'candlestick',
                        data: this.stockList,
                        itemStyle: {
                            normal: {
                                color: '#ef232a',
                                color0: '#14b143',
                                borderColor: '#ef232a',
                                borderColor0: '#14b143'
                            }
                        },
                        /*markArea: {
                            silent: true,
                            itemStyle: {
                                normal: {
                                    color: 'Honeydew'
                                }
                            },
                            data: fenduans()
                        },*/
                        markPoint: {
                            label: {
                                normal: {
                                    formatter: function (param) {
                                        return param != null ? Math.round(param.value) : '';
                                    }
                                }
                            },
                            data: [
                                {
                                    name: 'highest value',
                                    type: 'max',
                                    valueDim: 'highest'
                                },
                                {
                                    name: 'lowest value',
                                    type: 'min',
                                    valueDim: 'lowest'
                                },
                                {
                                    name: 'average value on close',
                                    type: 'average',
                                    valueDim: 'close'
                                }
                            ],
                            tooltip: {
                                formatter: function (param) {
                                    return param.name + '<br>' + (param.data.coord || '');
                                }
                            }
                        },
                        markLine: {
                            symbol: ['none', 'none'],
                            data: [
                                [
                                    {
                                        name: 'from lowest to highest',
                                        type: 'min',
                                        valueDim: 'lowest',
                                        symbol: 'circle',
                                        symbolSize: 10,
                                        label: {
                                            normal: { show: false },
                                            emphasis: { show: false }
                                        }
                                    },
                                    {
                                        type: 'max',
                                        valueDim: 'highest',
                                        symbol: 'circle',
                                        symbolSize: 10,
                                        label: {
                                            normal: { show: false },
                                            emphasis: { show: false }
                                        }
                                    }
                                ]
                            ]
                        }
                    }, {
                        name: 'MA5',
                        type: 'line',
                        data: this.calculateMA(5, this.stockList),
                        smooth: true,
                        lineStyle: {
                            normal: {
                                opacity: 0.5
                            }
                        }
                    }, {
                        name: 'MA10',
                        type: 'line',
                        data: this.calculateMA(10),
                        smooth: true,
                        /*标线的样式*/
                        lineStyle: {
                            normal: {opacity: 0.5}
                        }
                    }, {
                        name: 'MA20',
                        type: 'line',
                        data: this.calculateMA(20),
                        smooth: true,
                        lineStyle: {
                            normal: {opacity: 0.5}
                        }
                    }, {
                        name: 'MA30',
                        type: 'line',
                        data: this.calculateMA(30),
                        smooth: true,
                        lineStyle: {
                            normal: {opacity: 0.5}
                        }
                    }, {
                        name: 'Volumn',
                        type: 'bar',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: myVols,
                        itemStyle: {
                            normal: {
                                color(params) {
                                    let colorList;
                                    if (myStockList[params.dataIndex][1] > myStockList[params.dataIndex][0]) {
                                        colorList = '#ef232a';
                                    } else {
                                        colorList = '#14b143';
                                    }
                                    return colorList;
                                },
                            }
                        }
                    }, {
                        name: 'MACD',
                        type: 'bar',
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                        data: this.macds,
                        itemStyle: {
                            normal: {
                                color(params) {
                                    let colorList;
                                    if (params.data >= 0) {
                                        colorList = '#ef232a';
                                    } else {
                                        colorList = '#14b143';
                                    }
                                    return colorList;
                                },
                            }
                        }
                    }, {
                        name: 'DIF',
                        type: 'line',
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                        data: this.difs
                    }, {
                        name: 'DEA',
                        type: 'line',
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                        data: this.deas
                    }
                    ]
                };
            },
            /*MA计算公式*/
            calculateMA(dayCount) {
                const result = [];
                for (let i = 0, len = this.times.length; i < len; i++) {
                    //console.log(this.stockList[i][0]);
                    if (i < dayCount) {
                        result.push('-');
                        continue;
                    }
                    let sum = 0;
                    for (let j = 0; j < dayCount; j++) {
                        sum += this.stockList[i - j][1];
                    }
                    result.push((sum / dayCount).toFixed(2));
                }
                return result;
            }
        }
    };
</script>
